package com.ctn.information;


import com.actionbarsherlock.view.MenuItem;
import com.ctn.information.content.NewsFragment;
import com.ctn.information.menu.MenuSystemFragment;
import com.ctn.information.menu.MenuTopicListFragment;
import com.ctn.information.util.AppUtil;
import com.ctn.information.util.SwitchFragmentUtil;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

/**
 * 主框架，左右滑动隐藏菜单
 * 左滑动或点击标题栏的左图标，左边隐藏菜单栏侧滑可见
 * 右滑动或点击标题栏的右图标，右边隐藏菜单栏侧滑可见
 * 
 * @author HLJ
 *
 */
@SuppressLint("ResourceAsColor") 
public class MainActivity extends SlidingFragmentActivity {

	/**
	 * 一级栏目菜单
	 */
	MenuTopicListFragment menuList = null;
	
	/**
	 * 个性设置菜单（个人中心）
	 */
	MenuSystemFragment menuSys = null;
	
	/**
	 * Content View载体
	 */
	Fragment mContent = null;
	
	/**
	 * Action Bar副标题
	 */
	TextView subTitle = null;
	
	/**
	 * 保存滑动后的X坐标数（用于菜单栏的滑动开关）
	 */
	static float lastValue = -1F;
	private Context my;
	/**
	 * 获取副标题View
	 * @return
	 */
	public TextView getSubTitle(){
		return subTitle;
	}
	
	/**
	 * 创建视图
	 */
    @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        my=this;
        /**
         * 设置隐藏菜单视图        
         */
        /** 第一菜单（左边隐藏菜单） */
        setBehindContentView(R.layout.menu_frame);
        
        /**
         * 获取滑动隐藏菜单实例
         */
        /** -----------------Sliding Menu---------------- */
        SlidingMenu sm = getSlidingMenu();
        AppUtil.SLIDING_MENU = sm;	/** 存储Sliding Menu */
        sm.setMode(SlidingMenu.LEFT_RIGHT);
        sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setFadeDegree(0.35f);
		sm.setBehindOffset(AppUtil.SLIDING_MENU_OFFSET);
		
		/** 第二菜单（右边隐藏菜单） */
		sm.setSecondaryMenu(R.layout.menu_frame_two);
		sm.setSecondaryShadowDrawable(R.drawable.shadowright);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		/** -----------------Sliding Menu---------------- */
		
		/**
		 * 检测Bundle是否存在，如果存在直接获取所需Content
		 */
		if (savedInstanceState == null) {
			FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
			menuList = new MenuTopicListFragment();
			t.replace(R.id.menu_frame, menuList);
			t.commit();
			menuSys = new MenuSystemFragment(my);
			getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame_two, menuSys)
			.commit();
			mContent = new NewsFragment();
			/** 绑定Fragment */
			SwitchFragmentUtil.bindTopicFragment(getResources().getString(R.string.app_menu_topic_id_1), mContent);
		} else {
			mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
			menuList = (MenuTopicListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
			menuSys = (MenuSystemFragment)this.getSupportFragmentManager().findFragmentById(R.layout.menu_frame_two);
		}
		
		
		/**
		 * 设置标题bar的样式 
		 */
		/** ------------------Action Bar---------------- */
		com.actionbarsherlock.app.ActionBar bar = getSupportActionBar();
		bar.setDisplayShowCustomEnabled(true);	/** 开启自定义Title View */
		bar.setCustomView(R.layout.title_bar);	/** 自定义Title View Layout */
		subTitle = (TextView) bar.getCustomView().findViewById(R.id.title_sub_bar_text);	/** 获取SubTitle View */
		subTitle.setText(R.string.app_bar_subtitle);	/** 设置副标题文本 */
		/**
		 * Action Bar 触发 Sliding Menu
		 */
		bar.getCustomView().setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				switch (arg1.getAction()) {
				case MotionEvent.ACTION_DOWN:
					lastValue = arg1.getX();
					break;
				case MotionEvent.ACTION_MOVE:
					if (lastValue == -1F) {
						lastValue = arg1.getX();
					}
					float diff_l = arg1.getX() - lastValue;
					float diff_r = lastValue - arg1.getX();
					if (diff_l > 0F && diff_l > AppUtil.DRAG_DIFF_DISTANCE) {
						AppUtil.SLIDING_MENU.showMenu();
					}else if(diff_r > 0F && diff_r > AppUtil.DRAG_DIFF_DISTANCE){
						AppUtil.SLIDING_MENU.showSecondaryMenu();
					}
					break;
				case MotionEvent.ACTION_UP:
						lastValue = -1F;
					break;
				default:
					break;
				}
				return true;
			}
		});
		bar.setDisplayHomeAsUpEnabled(true);
		bar.setIcon(R.drawable.menu_news_icon);	/** 设置图标 */
		Resources res = getResources();
		Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.bar_background_color);
		BitmapDrawable bd = new BitmapDrawable(res, bmp);
		bar.setBackgroundDrawable(bd);	/** 设置背景 */
		setSlidingActionBarEnabled(true);
		/** ------------------Action Bar---------------- */
		
		/**
		 * 中间区域加载View
		 */
		/** ------------------View---------------- */
		setContentView(R.layout.content_frame);
		getSupportFragmentManager().beginTransaction().add(R.id.content_frame, mContent).commit();
		/** ------------------View---------------- */
		
    }
    
    @Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		getSupportFragmentManager().putFragment(outState, "mContent", mContent);
	}

	/**
     * 切换中心区域面板
     *  
     * @param fragment
     */
	public void switchContent(Fragment fragment) {
		/**
		 * 替换中心区域内容
		 */
		getSupportFragmentManager().beginTransaction().detach(mContent).replace(R.id.content_frame, fragment).attach(fragment).addToBackStack(null)
		.commit();
		mContent = fragment;
		/**
		 * 替换时的动画效果
		 */
		Handler h = new Handler();
		h.postDelayed(new Runnable() {
			public void run() {
				getSlidingMenu().showContent();
			}
		}, 50);
	}
    

    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	/**
    	 * Action Bar两边的图标操作
    	 */
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;
		case R.id.github:
			showSecondaryMenu();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
    
    @Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
    
    /**
     * 退出
     */
	@Override
	public void onBackPressed() {
		AppUtil.QuitHintToast(this);
	}    
}
